<?php
App::uses('AppModel', 'Model');
/**
 * User Model
 *
 * @property UserGroup $UserGroup
 * @property TicketAdvisory $TicketAdvisory
 * @property UserBinding $UserBinding
 * @property UserOrder $UserOrder
 */
class User extends AppModel {

	public $actsAs = array('Pagination');
/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'user_group_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		)
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'UserGroup' => array(
			'className' => 'UserGroup',
			'foreignKey' => 'user_group_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'SysPhoto' => array(
				'className' => 'Album.SysPhoto',
				'foreignKey' => 'sys_photo_id',
				'conditions' => '',
				'fields' => '',
				'order' => ''
		),
		'UserState' => array(
				'className' => 'UserState',
				'foreignKey' => 'user_state_id',
				'conditions' => '',
				'fields' => '',
				'order' => ''
		)
	);

	/**
	 * 手机号唯一
	 * @author zmx@gootop.net
	 * @Date 2012-12-5
	 * @param
	 * @return
	 */
	function checkRegisterMobile($check){
		if($this->find('count',array('conditions'=>array('User.mobile'=>$check['mobile'])))){
			return false;
		}
		return true;
	}
	
	/**
	 * Email 唯一
	 * @author zmx@gootop.net
	 * @Date 2012-12-5
	 * @param
	 * @return
	 */
	function checkRegisterEmail($check){
		if($this->find('count',array('conditions'=>array('User.email'=>$check['email'])))){
			return false;
		}
		return true;
	}
	
	/**
	 * 确认密码检测
	 * @author zmx@gootop.net
	 * @Date 2012-11-15
	 * @param
	 * @return
	 */
	function checkConfirmPassword($check,$user){
		if($check['confirm_password']==$user['User']['password']){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 密码确认
	 * @author zmx@gootop.net
	 * @Date 2012-11-15
	 * @param
	 * @return
	 */
	function checkOldPassword($check,$ouser) {
		if($ouser['User']['password'] == AuthComponent::password($check['old_password'])){
			return true;
		}else{
			return false;
		}
	}
	
	function checkAgree($check){
		if($check['agree']==1){
			return true;
		}else{
			return false;
		}
	}
	
	
	/**
	 * 用户登陆
	 * @author mingxing.zhao@qq.com
	 * @Date 2013-12-18
	 * @param
	 * @return
	 */
	function userLogin($data){
		$username =$data['User']['username'];
		$password = $data['User']['password'];
		if($username==''||$password==''){
			return false;
		}
		$user = $this->find('first',array('conditions'=>array(
			'or' =>array('username'=>$username,'email'=>$username,'mobile'=>$username),
			'password' => AuthComponent::password($password)
		)));
		if ($user) {
			$user = $this->findById($user['User']['id']);
			$user['User']['UserGroup'] = $user['UserGroup'];
			return $user;
		} 
		return false;
	}
	
	function editPassword($data){
		$this->id = $data['User']['id'];
		$password = $data['User']['password'];
		$this->set('password',AuthComponent::password($password));
		return $this->save();
	}
	
	/**
	 * 用户注册
	 * @author zmx@gootop.net
	 * @Date 2012-11-15
	 * @param
	 * @return
	 */
	function register($user,$user_group_id = 2){
			$this->validate['confirm_password']=array(
					'rule1'=>array(
							'rule' => array('checkConfirmPassword',$user),
							'message' => '确认密码与密码不匹配',
							'allowEmpty' => false
					)
			);
			$this->validate['agree']=array(
					'rule1'=>array(
							'rule' => array('checkAgree',$user),
							'message' => '同意我们的服务条款',
							'allowEmpty' => false
					)
			);
			$this->validate['mobile']=array(
					'rule1'=>array(
							'rule' => '[^1\d{10}]',
							'message' => '手机号码格式不正确',
							'allowEmpty' => false
					),
					'isExist'=>array(
							'rule' => array('checkRegisterMobile'),
							'message' => '手机号已存在'
					)
			);
			$this->validate['email']=array(
					'email'=>array(
							'rule' => 'email',
							'message' => '邮箱格式不正确',
							'allowEmpty' => false
					),
					'isExist'=>array(
							'rule' => array('checkRegisterEmail'),
							'message' => '邮箱已存在'
					)
			);
				
			$user['User']['password'] = $user['User']['password']==''?$user['User']['password']:AuthComponent::password($user['User']['password']);
			$user['User']['user_group_id'] = $user_group_id;
			$user['User']['user_state_id'] = 1;
			//trans save
			$errorHandler = 0;
			$dataSource = $this->getDataSource();
			$dataSource->begin();
		
			if(!$this->save($user)){
				$errorHandler++;
			}
		
			if($errorHandler){
				$dataSource->rollback();
				return false;
			}else{
				$dataSource->commit();
				return $this->id;
			}
		}
	
	/**
	 * 分页条件
	 * @author mingxing.zhao@qq.com
	 * @Date 2012-12-20
	 * @return Array
	 */
	function pageParam($action){
		return array(
				"colNames"=>array(
						'ID','用户类型','用户名','真实姓名','性别','手机','邮箱','积分','状态','注册时间','操作'
				),
				"colModel"=>array(
						array("name"=>'User.id',"width"=>'50',"sortable"=>true,"align"=>"right"),
						array("name"=>'UserGroup.id',"width"=>"90","sortable"=>true,"align"=>"center"),
						array("name"=>'User.username',"width"=>"80","sortable"=>true,"align"=>"left"),
						array("name"=>'User.name',"width"=>"90","sortable"=>true,"align"=>"left"),
						array("name"=>'User.sex',"width"=>"30","sortable"=>true,"align"=>"center"),
						array("name"=>'User.mobile',"width"=>"100","sortable"=>true,"align"=>"center"),
						array("name"=>'User.email',"width"=>"150","sortable"=>true,"align"=>"left"),
						array("name"=>'User.credit',"width"=>"50","sortable"=>true,"align"=>"center"),
						array("name"=>'UserState.id',"width"=>"50","sortable"=>true,"align"=>"center"),
						array("name"=>'User.created',"width"=>"150","sortable"=>true,"align"=>"center"),
						array("name"=>'act',"width"=>"150","sortable"=>false,"align"=>"center")
				),
				"action"=>$action,
				'sortname'=>'id',
				'sortorder'=>'DESC'
		);
	}
	
	/**
	 * 分页数据
	 * @author mingxing.zhao@qq.com
	 * @param array
	 * @date 2013-12-20
	 * @return json
	 *
	 */
	function jsonData($res){
		$rowN = array();
		$i=0;
		foreach($res['rows'] as $k => $value){
			$rowN[$i]['id'] = $value['User']['id'];
			$rowN[$i++]['cell'] = array(
					$value['User']['id'],
					$value['UserGroup']['title'],
					$value['User']['username'],
					$value['User']['name'],
					sex($value['User']['sex']),
					$value['User']['mobile'],
					$value['User']['email'],
					$value['User']['credit'],
					$value['UserState']['title'],
					$value['User']['created'],
					''
			);
		}
		$res['rows'] = $rowN;
		return json_encode($res);
	}
	
	function editAdminPassword($user){
		$ouser = $this->findById($user['User']['id']);
		$this->validate['old_password']=array(
				'rule1'=>array(
						'rule' => array('notempty'),
						'message' => '旧密码不能为空'
				),
				'rule2'=>array(
						'rule' => array('checkOldPassword',$ouser),
						'message' => '旧密码不正确'
				)
		);
		$this->validate['confirm_password']=array(
				'rule2'=>array(
						'rule' => array('checkConfirmPassword',$user),
						'message' => '确认密码不正确',
						'allowEmpty' => false
				)
		);
		$this->set($user);
		if(!$this->validates())return false;
		$ouser['User']['password'] = AuthComponent::password($user['User']['password']);
		return $this->save($ouser);
	}

}
